#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
/*
 * Zenlayer.com Inc.
 * Copyright (c) 2014-2020 All Rights Reserved.
 */
package ${package}.${artifactId}.utils;

import com.fasterxml.jackson.${artifactId}.JsonFactory;
import com.fasterxml.jackson.${artifactId}.JsonGenerator;
import com.fasterxml.jackson.${artifactId}.JsonProcessingException;
import com.fasterxml.jackson.${artifactId}.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.ObjectUtils;

import java.io.IOException;
import java.io.StringWriter;

/**
 * @author yangshen
 * @version ${symbol_dollar} Id: JacksonUtil.java, v 0.1  yangshen Exp ${symbol_dollar}
 * @date 2019-11-29 15:10:03
 */

public class JacksonUtil {
    private static final ObjectMapper mapper = new ObjectMapper();

    static {
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    }

    public static String bean2Json(Object obj) {
        StringWriter sw = new StringWriter();
        try {
            JsonGenerator gen = new JsonFactory().createGenerator(sw);
            mapper.writeValue(gen, obj);
            gen.close();
            return sw.toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T json2Bean(String jsonStr, Class<T> objClass) {
        try {
            return mapper.readValue(jsonStr, objClass);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T json2Bean(String jsonStr, JavaType javaType) {
        try {
            return mapper.readValue(jsonStr, javaType);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T json2BeanByR(String jsonStr, TypeReference<T> objClass) {
        try {
            return mapper.readValue(jsonStr, objClass);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> String bean2JsonToString(T object) {
        try {
            return mapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return ObjectUtils.identityToString(object);
    }

    public static <T, S> T beanCopy(S original, Class<T> change) throws IOException {
        String originalString = bean2Json(original);
        return json2Bean(originalString, change);
    }

    public static <T, S> T beanListCopy(S original, TypeReference<T> objClass) throws IOException {
        String originalString = bean2Json(original);
        return json2BeanByR(originalString, objClass);
    }

}